//package com.example.zyxdemo.controller;
//
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.ai.chat.ChatClient;
//import org.springframework.ai.chat.model.ChatModel;
//import org.springframework.ai.chat.prompt.Prompt;
//import org.springframework.ai.chat.prompt.PromptTemplate;
//import org.springframework.ai.parser.BeanOutputParser;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//import reactor.core.publisher.Mono;
//
//import java.net.HttpURLConnection;
//import java.net.URL;
//import java.time.Duration;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * @author: zhangyx
// * @create: 2022-12-02 10:17
// **/
//
//@RestController
//@Slf4j
//@RequestMapping("/order/api")
//public class Demo1Controller {
//    private final ChatModel deepSeekChatModel;
//
//    public Demo1Controller (ChatModel chatModel) {
//        this.deepSeekChatModel = chatModel;
//    }
//
//    private final BeanOutputParser<Intent> outputParser =
//            new BeanOutputParser<>(Intent.class); // 创建输出解析器
//
//    @GetMapping("list1")
//    public void list1() {
//
//        // 1. 构建 Prompt 模板 (明确指令 + 输出格式要求)
//        String promptTemplate = """
//            请识别用户输入的意图并提取关键实体。按以下 JSON 格式返回结果：
//            {format}
//
//            可选意图类型：
//            - CHECK_BALANCE: 查询账户余额
//            - TRANSFER: 转账请求
//            - COMPLAINT: 用户投诉
//            - GREETIN: 问候语
//            - UNKNOWN: 未知意图
//
//            用户输入：
//            {userInput}
//            """;
//
//        // 2. 绑定动态变量 (用户输入 + JSON 格式描述)
//        Map<String, Object> model = new HashMap<>();
//        model.put("userInput", "转账");
//        model.put("format", outputParser.getFormat()); // 注入格式描述
//
//        // 3. 创建 Prompt
//        PromptTemplate pt = new PromptTemplate(promptTemplate);
//        Prompt prompt = pt.create(model);
//
//        // 4. 调用 LLM 并解析结果
//        String llmOutput = chatClient.call(prompt).getResult().getOutput().getContent();
//        outputParser.parse(llmOutput); // 自动转换为 Intent 对象
//    }
//
//    @GetMapping("list2")
//    public void list2(){
////        OpenAiService service = new OpenAiService("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", Duration.ofSeconds(60));
////
////        ChatCompletionRequest request = ChatCompletionRequest.builder()
////                .model("gpt-3.5-turbo")
////                .messages(Collections.singletonList(new ChatMessage("user", "Hello!")))
////                .build();
////
////        ChatCompletionResult result = service.createChatCompletion(request);
////        System.out.println(result);
//    }
//
//    @GetMapping("/test-openai-connection")
//    public String testConnection() {
//        try {
//            URL url = new URL("https://api.openai.com");
//            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//            connection.setConnectTimeout(30000);
//            connection.connect();
//            return "连接成功! 响应码: " + connection.getResponseCode();
//        } catch (Exception e) {
//            return "连接失败: " + e.getMessage();
//        }
//    }
//
//    public Intent detectIntent(String userInput) {
//        String promptTemplate = """
//            请识别用户输入的意图并提取关键实体。按以下 JSON 格式返回结果：
//            {format}
//
//            可选意图类型：
//            - CHECK_BALANCE: 查询账户余额
//            - TRANSFER: 转账请求
//            - COMPLAINT: 用户投诉
//            - GREETING: 问候语
//            - UNKNOWN: 未知意图
//
//            用户输入：
//            {userInput}
//            """;
//        // 1. 构建动态参数
//        Map<String, Object> model = Map.of(
//                "userInput", userInput,
//                "format", """
//            {
//              "intent": "CHECK_BALANCE|TRANSFER|...",
//              "entities": {"amount": 100, "targetAccount": "xxx"}
//            }"""
//        );
//        PromptTemplate PT = new PromptTemplate(promptTemplate);
//        // 2. 创建Prompt（带超时标记）
//        Prompt prompt = PT.create(model);
//
//        // 3. 调用API（异步非阻塞）
//        return Mono.fromCallable(() -> chatClient.call(prompt))
//                .timeout(Duration.ofSeconds(25))
//                .map(response -> outputParser.parse(response.getResult().getOutput().getContent()))
//                .block();
//    }
//
//    public static void main(String[] args) throws Exception {
//
//        try {
//            System.setProperty("java.net.useSystemProxies", "true");
//            URL url = new URL("https://api.openai.com");
//            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//            connection.setConnectTimeout(30000);
//            connection.connect();
//
//        } catch (Exception e) {
//           e.printStackTrace();
//        }
//        // 创建信任所有证书的SSLContext（仅用于测试环境）
////        SSLContext sslContext = SSLContext.getInstance("TLS");
////        sslContext.init(null, new TrustManager[]{
////                new X509TrustManager() {
////                    public void checkClientTrusted(X509Certificate[] chain, String authType) {}
////                    public void checkServerTrusted(X509Certificate[] chain, String authType) {}
////                    public X509Certificate[] getAcceptedIssuers() { return null; }
////                }
////        }, new SecureRandom());
////
////// 应用到全局设置
////        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
////        HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
////        System.setProperty("java.net.useSystemProxies", "true");
//////        System.setProperty("java.net.preferIPv4Stack", "true");
////        HttpClient client = HttpClient.newBuilder()
////                .version(HttpClient.Version.HTTP_2)
////                .connectTimeout(Duration.ofSeconds(30))
////                .sslContext(SSLContext.getDefault()) // 或自定义SSLContext
////                .build();
////
////        HttpRequest request = HttpRequest.newBuilder()
////                .uri(URI.create("https://api.openai.com/v1/chat/completions"))
////                .header("Content-Type", "application/json")
////                .header("Authorization", "Bearer YOUR_API_KEY")
////                .timeout(Duration.ofSeconds(30))
////                .POST(HttpRequest.BodyPublishers.ofString(""))
////                .build();
////
////        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
////        System.out.println(response.statusCode());
////        System.out.println(response.body());
//    }
//}
